<script lang="ts" setup>
import {type VoteData, VoteResultShow, VoteType} from "../../network/types/Vote.ts";
import {ref} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";
import {useTopicReadStore} from "../../store/TopicReadStore.ts";

interface Props {
  tid: number,
  data: VoteData,
}

interface OptionGroupValue {
  [key: number]: number[]
}

const props = defineProps<Props>()
const optionGroup = ref<OptionGroupValue>({})
const topicReadStore = useTopicReadStore();

const submitBetTopic = (id: number) => {
  console.log(id)
  const item = props.data.options.find(it => it.id === id);
  if (!item) {
    ElMessage.error('错误的选项')
    return
  }
  ElMessageBox.prompt(`你选择的项目为 < ${item.label} > 请选择投注金额(以铜币计)`, '菠菜投注', {
    customClass: 'alert-message',
    inputType: 'number'
  }).then(({value}) => {
    const money = Number(value)
    topicReadStore.vote(props.tid, [id, money]).then(res => {
      console.log(res)
    }).catch(r => {
      console.error(r)
      if (r.error) {
        ElMessage.error(r.error[0])
      }
    })
  })
}

const submitVoteTopic = () => {
  const voteIds = Object.values(optionGroup.value).flatMap(i => i)
  const selected = props.data.options.filter(it => voteIds.includes(it.id)).map(i => `〇 ${i.label}`);
  const arr = ['你选择的项目为: ', ...selected, '确定要提交投票吗？']
  // 确认弹窗
  ElMessageBox.confirm(arr.join('\n'), '提交投票', {customClass: 'alert-message',}).then(() => {
    topicReadStore.vote(props.tid, voteIds).then(res => {
      console.log(res)
    }).catch(r => {
      console.error(r)
      if (r.error) {
        ElMessage.error(r.error[0])
      }
    })
  })
}

const progressColor = (percent: number) => {
  // 确保输入在0-100 范围内
  percent = Math.max(0, Math.min(100, percent));

  // 将百分比转换为0-1 范围
  const ratio = percent / 100;

  const per = Math.round(255 * ratio)
  // 计算RGB值
  const r = per
  // const r = Math.round(255 * ratio);
  const g = 0;
  // const g = Math.round(255 * ratio / 2);
  const b = 255 - per;

  // 将RGB值转换为十六进制
  const toHex = (v: number) => {
    const hex = v.toString(16);
    return hex.length === 1 ? '0' + hex : hex;
  };

  return `#${toHex(r)}${toHex(g)}${toHex(b)}`;
};
const optionTitle = (index: number) => {
  const totalCount = props.data.options.filter(i => i.groupIndex === index).map(i => i.count).reduce((a, b) => a + b, 0)
  return props.data.groupCount > 1 ? `分组${index}; 总票数: ${totalCount}` : '选项'
}

const expired = (t: number | undefined) => t ? new Date().getTime() / 1000 > t : false

</script>

<template>
  <div>
    <h4>
      <span v-if="data.type===VoteType.VOTE_TOPIC">投票</span>
      <span v-if="data.type===VoteType.BET_TOPIC">菠菜</span>
      <span v-if="data.type===VoteType.SCORE_TOPIC">评分统计</span>
      <span v-if="data.type===VoteType.SCORE_REPLY">评分: &nbsp;&nbsp;{{ data?.score }}</span>
    </h4>
    <div>
      <!--提示文字-->
      <div class="notice-text">
        <span v-if="data.resultShow!==VoteResultShow.IMMEDIATELY">
          <span v-if="data.resultShow===VoteResultShow.AFTER_VOTE">投票后查看结果;</span>
          <span v-if="data.resultShow===VoteResultShow.AFTER_END">结束后查看结果;</span>
        </span>
        <span v-if="data.maxSelect">
          <span v-if="data.groupCount && data.groupCount>1">每组</span>最多选择 {{ data.maxSelect }} 项;
        </span>
        <span v-if="data.reputation">
          需要至少 {{ data.reputation }} 版面声望;
        </span>
        <span v-if="data.end">
          于 {{ data.end?.full }} 结束
          <span v-if="expired(data.end?.seconds)" style="color: red">[已结束]</span>
        </span>
        <span v-if="data.total">参与人数: {{ data.total }};</span>
        <span v-if="data.totalCount">总票数: {{ data.totalCount }};</span>
        <span v-if="data.totalMoney">总金额: {{ data.totalMoney }};</span>
        <span v-if="data.groupCount && data.groupCount>1">分组数量: {{ data.groupCount }};</span>
        <span v-if="data.min && data.type===VoteType.VOTE_TOPIC">最小投注金额: {{ data.min }};</span>
        <span v-if="data.max && data.type===VoteType.VOTE_TOPIC">最大投注金额: {{ data.max }};</span>
        <span v-if="data.type===VoteType.SCORE_TOPIC">评分范围: {{ data.min }} ~ {{ data.max }};</span>
        <span v-if="data.title">{{ data.title }} {{ (data.totalScore / data.total).toFixed(2) }}</span>
      </div>
      <!--投票-->
      <div v-if="data.type===VoteType.VOTE_TOPIC">
        <template v-for="index in data.groupCount">
          <!--最多选一项的情况-->
          <el-checkbox-group
              v-model="optionGroup[index]"
              :disabled="expired(data.end?.seconds)"
              :max="data.maxSelect"
              class="vote-option-group"
          >
            <!--选项表格-->
            <el-table :data="data.options.filter(it => it.groupIndex===index)">
              <!--分组标题-->
              <el-table-column :label="optionTitle(index)">
                <template #default="{row}">
                  <el-checkbox :label="row.label" :value="row.id"/>
                </template>
              </el-table-column>
              <!--票数-->
              <el-table-column :width="100" label="票数" prop="count" sortable/>
              <!--占比-->
              <el-table-column label="占比">
                <template #default="{row}">
                  <el-progress :color="progressColor" :percentage="row.countPerFixed"/>
                </template>
              </el-table-column>
            </el-table>
          </el-checkbox-group>
        </template>
        <el-button v-if="!expired(data.end?.seconds)" type="success" @click="submitVoteTopic">提交</el-button>
      </div>
      <!-- 菠菜-->
      <div v-if="data.type===VoteType.BET_TOPIC" class="vote-option-group">
        <!--选项表格-->
        <el-table :data="data.options">
          <el-table-column v-if="!expired(data.end?.seconds)" :width="85" label="投注">
            <template #default="{row}">
              <el-button type="success" @click="submitBetTopic(row.id)">投注</el-button>
            </template>
          </el-table-column>
          <!--分组标题-->
          <el-table-column label="选项">
            <template #default="{row}">
              <span>{{ row.label }}</span>
              <el-tag v-if="row.id===data.successId" effect="dark" style="margin-left: 10px" type="danger">胜出</el-tag>
            </template>
          </el-table-column>
          <!--票数-->
          <el-table-column :width="100" label="人数" prop="count" sortable/>
          <!--人数占比-->
          <el-table-column label="人数占比">
            <template #default="{row}">
              <el-progress :color="progressColor" :percentage="row.countPerFixed"/>
            </template>
          </el-table-column>
          <!--金额-->
          <el-table-column :width="100" label="金额" prop="money" sortable/>
          <el-table-column label="金额占比">
            <template #default="{row}">
              <el-progress :color="progressColor" :percentage="row.moneyPerFixed"/>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <!--评分统计-->
      <div v-if="data.type===VoteType.SCORE_TOPIC" class="vote-option-group">
        <el-table v-if="data.scoreResults.length>0" :data="data.scoreResults">
          <el-table-column label="评分范围">
            <template #default="{row}">
              <span>{{ row.score * 2 - 1 }}</span> ~
              <span>{{ row.score * 2 }}</span>
            </template>
          </el-table-column>
          <el-table-column :width="100" label="人数" prop="count" sortable/>
          <!--占比-->
          <el-table-column label="占比">
            <template #default="{row}">
              <el-progress :color="progressColor" :percentage="row.countPerFixed"/>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>

<style scoped>
.notice-text > span {
  margin-right: 5px;
}

.vote-option-group {
  border: 1px dashed #003cff;
  padding: 5px;
  margin-bottom: 3px;
  display: block
}
</style>